//新增问题的弹出层
var openSaveKnowledgeBase;

//
var openUpdateKnowledgeBase;

layui.use(['form', 'layer', 'laydate', 'table', 'laytpl', 'element','upload'], function () {
    var element = layui.element;
    var laydate = layui.laydate;
    var layer = layui.layer;


    var upload = layui.upload;

    //执行实例
    var uploadInst = upload.render({
        elem: '#import' //绑定元素
        ,url: baseUrl + '/knowledgeBase/importKnowledgeBase' //上传接口
        ,method : "post"
        ,accept: 'file' //普通文件
        ,multiple: true
        ,data: {packageId: packageId}
        ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            console.log(parent.selNode);
            if(parent.selNode == undefined || parent.selNode == null || parent.selNode == ""){
                layer.msg("请选择指定的知识库类型，再进行导入操作吧！");
                return;
            }
            if(packageId==undefined ||packageId==null || packageId==""){
                layer.msg("请选择指定的知识库类型，再进行导入操作吧！");
                return;
            }else{
                layer.load(); //上传loading
            }
        }
        ,done: function(res){
            if(res.code<=0){
                layer.msg(res.msg);
            }else{
                layer.msg("导入成功.");
            }
            layer.closeAll('loading'); //关闭loading
        }
        ,error:function (e) {
            layer.msg("导入异常！！！");
            layer.closeAll('loading'); //关闭loading
        }
    });

    //日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = "'" + date.getFullYear() + "-" + month + "-" + strDate
            + " " + hours + ":" + minutes + ":" + seconds + "'";
        return currentdate;
    }

    var getNowFormatDate = getNowFormatDate();
    var dateMin = laydate.render({
        elem: '#regDateMin',
        type: 'datetime',
        min: "1970-01-01",//设置min默认最小值
        max: getNowFormatDate,//设置一个默认最大值
        done: function (value, dates) {
            dateMax.config.min = {
                year: dates.year,
                month: dates.month - 1, //关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds: 0
            };
        }
    });
    var dateMax = laydate.render({
        elem: '#regDateMax',
        type: 'datetime',
        min: "1970-01-01",//设置min默认最小值
        max: getNowFormatDate,
        done: function (value, dates) {
            dateMin.config.max = {
                year: dates.year,
                month: dates.month - 1,//关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds: 0
            }
        }
    });
    var form = layui.form,
        layer = layui.layer;
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;


    //layui请求后台返回数据表格的数据
    var tableIns = table.render({
        where: {key: $("#key").val(),packageId:packageId,affectType:affectType,knowledgeType:$("#knowledgeType").val(),
            keyworld:$("#keyworld").val(),howAskQuestion:$("#howAskQuestion").val(),refPackageId:refPackageId,
            createUserId:$("#createUserId").val(),canSearchAll:$("#canSearchAll").val()
        },//搜索的关键字
        elem: '#knowledgeBaseList',
        url: 'queryKnowledgeBaseBySearch',
        cellMinWidth: 95,
        page: true,
        // height : "full-175",
        limit: 10,
        limits: [10, 20, 30, 40, 50],
        id: "newsListTable",
        cols: [
            [
                /*{type: "checkbox", fixed:"left", width:50 },*/
                {field: 'title', title: '标题', width: 300},
                {
                    field: 'type', title: '问法', align: 'center', minWidth: 350, templet: function (d) {

                    //所有问题问法
                    var questions = d.howAskQuestions;

                    if (questions != null && questions.length > 0) {

                        //获取随机索引
                        var number = parseInt(Math.random() * (questions.length), 10);

                        //随机返回
                        return questions[number];
                    }

                    return null;
                }
                },
                {
                    field: 'keyworlds', title: '关键词(个)', align: 'center', minWidth: 150, templet: function (d) {

                    var keyworlds = d.keyworlds;

                    var keyworldslength = 0;

                    for (var i in keyworlds) {

                        keyworldslength++;
                    }

                    return keyworldslength;
                }
                },
                {field: 'knowledgeType', title: '类型',minWidth:110, align:'center',templet:function (d) {
                    if (d.knowledgeType != null) {
                        if (d.knowledgeType == "COMMON") {
                            return "一般问题"
                        }
                        return "业务问题";
                    }
                }},
                {
                    field: 'modTime', title: '更新时间', align: 'center', minWidth: 200

                },

                {title: '操作', width: 170, toolbar: '#techniqueListBar', fixed: "right", align: "center"}
            ]
        ]
    });

    //监听表格工具条,完成对表格的编辑和删除
    table.on('tool(knowledgeBaseList)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象

        if (layEvent === 'del') { //删除
            layer.confirm('真的删除此条数据吗?', function (index) {
                //弹出loading层,友好提示
                var loading = layer.load(1, {
                    shade: [0.1,'#fff'] //0.1透明度的白色背景
                });

                //根据Id用ajax删除数据,dataId为所需要删除的数据ID,url为请求地址
                $.ajax({
                    url: "deleteById",
                    type: "post",
                    data: {"id": data.id},
                    dataType:"json",
                    success: function (callback) {
                        layer.close(loading);
                        if (callback.code == '1') {
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.msg("删除成功");
                        }else{
                            layer.msg(callback.msg);
                        }
                        layer.close(index);
                    },
                    error: function (callback) {

                        layer.close(loading);
                        layer.msg("操作异常");
                        layer.close(index);
                    }

                })


            });
        } else if (layEvent === 'edit') { //编辑
            console.log(data.override);
            if(data.override == true){
                layer.msg(" 该公共知识库已被覆盖并自动新建同标题自定义知识库");
                return;
            }
            var winName = self.frameElement.getAttribute('id');
            openUpdateKnowledgeBase = window.parent.layer.open({
                type: 2,
                title: '编辑知识库',
                /*fixed:true,
                 resize:false,*/
                area: ['57%', '70%'],
                btn: ['确 定', '取 消']
                , yes: function (index, layero) {


                    //获取iframe层的提交按钮对象
                    var submitButton = window.parent.layer.getChildFrame('button', index);

                    //我点!
                    submitButton.click();

                }
                , btn2: function (index, layero) {

                    window.parent.layer.msg("取消保存")
                    //return false 开启该代码可禁止点击该按钮关闭
                },
                //scrollbar: false,
                content: baseUrl+"/knowledgeBase/editKnowledgeBase?id=" + data.id+"&refPackageId="+refPackageId+"&brotherWinName="+winName+"&packageId="+packageId+"&affectType="+affectType//no表示没有滚动条模式
            });
            setTimeout(function(){
                window.parent.layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            },500);
            window.parent.layer.full(openUpdateKnowledgeBase);
        }
    });
    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {

        table.reload("newsListTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {key: $("#key").val(),packageId:packageId,affectType:affectType,knowledgeType:$("#knowledgeType").val(),keyworld:$("#keyworld").val(),howAskQuestion:$("#howAskQuestion").val()}
        })

    });


    //弹出添加问题
    function addOrEditKnowledgeBase(title) {
        var winName = self.frameElement.getAttribute('id');
        openSaveKnowledgeBase =  window.parent.layer.open({
            type: 2,
            title: title,
            area: ['57%', '73%'],
            btn: ['保存', '取消'],
            yes: function (index, layero) {

                //获取iframe层的提交按钮对象
                var submitButton = window.parent.layer.getChildFrame('button', index);

                //我点!
                submitButton.click();
                tableIns.reload();
            }
            , btn2: function (index, layero) {

                $("#cancel").click();
            },
            content:baseUrl + "/knowledgeBase/addKnowledgeBase?brotherWinName="+winName+"&packageId="+packageId+"&affectType="+affectType //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
        });
        setTimeout(function(){
            window.parent.layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                tips: 3
            });
        },500);
        window.parent.layer.full(openSaveKnowledgeBase);
    }


    //点击添加问题,弹框
    $("#add_btn").click(function () {
        addOrEditKnowledgeBase("添加问题");
    });


    //搜索标题框按回车进行搜索
    $(document).on({

        keydown:function (event) {
            if(event.keyCode==13){
                $("#search").click();
            }
        }

    },'#key')

    //监听选择框按回车进行搜索
    form.on("select(knowledgeType)",function (data) {
            $("#search").click();
            //更新渲染
            form.render('select')
    });

    $("#down").click(function () {
        var $eleForm = $("<a href='"+baseUrl+"/file/上传公共知识库模板.xlsx' download='上传公共知识库模板.xlsx'></a>");
        $(document.body).append($eleForm);
        //提交表单，实现下载
        $eleForm[0].click();
    });
    $("#exportExcel").click(function () {
        layer.confirm('目前仅支持导出1000条记录，是否继续执行导出?', function (index) {
            //弹出loading层,友好提示
            var loading = layer.load(1, {
                shade: [0.1,'#fff'] //0.1透明度的白色背景
            });
            try{
                $("#exportForm").attr("action",baseUrl+"/knowledgeBase/export");
                $("#exportForm").submit();
            }catch (e){
                layer.msg("导出操作异常");
            }finally {
                layer.close(loading);
                layer.close(index);
            }
        });
    });

});